package com.sc.outpatientsys.service.impl;

import com.sc.outpatientsys.entity.Medicine;
import com.sc.outpatientsys.entity.Student;
import com.sc.outpatientsys.mapper.MedicineMapper;
import com.sc.outpatientsys.service.IMedicineService;
import com.sc.outpatientsys.service.ex.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
@Service
@Slf4j
public class MedicineServiceImpl implements IMedicineService {
    @Autowired
    private MedicineMapper medicineMapper;
    @Override
    public void add(Medicine medicine) {
        String medcineName = medicine.getMed_Name();
        Medicine rst = medicineMapper.findByMedicineName(medcineName);
        //检测能否找到
        if(rst != null){
            throw new UserNameHasExistException("已有此药品");
        }
        // 插入
        Integer rows = medicineMapper.insertMedicine(medicine);
        if(rows != 1){
            throw new InsertException("药品添加过程中出现未知错误！");
        }
    }

    @Override
    public void update(Medicine medicine) {
        Integer rows = medicineMapper.updateMedicine(medicine);
        log.info(medicine.toString());
        if(rows != 1){
            throw new UpdateException("修改时出现未知错误");
        }
    }

    @Override
    public void delete(int med_ID) {
        Integer rows = medicineMapper.deleteMedicine(med_ID);
        if(rows != 1){
            throw new DeleteException("删除时出现位置错误");
        }
    }

    @Override
    public Medicine findById(int med_ID) {
        Medicine result = medicineMapper.findByMedicineID(med_ID);
        if (result == null){
            throw new NotFindException("未找到");
        }
        return result;
    }

    @Override
    public Medicine findByName(String med_name) {
        Medicine result = medicineMapper.findByMedicineName(med_name);
        if(result == null){
            throw  new NotFindException("未找到");
        }
        return result;
    }

    @Override
    public List<Medicine> findAll() {
        List<Medicine> result = medicineMapper.selectAllMedicine();
        if(result == null)
            throw new NotFindException("未找到");
        return result;
    }

    @Override
    public List<Medicine> findById_List(String Id_List) {
        String[] id_list_String = Id_List.split(",");
//        Integer id_list_Int[] = new Integer[id_list_String.length];
        List<Medicine> medicineList = new ArrayList<>();
        for (String s : id_list_String) {
            int id_int = Integer.parseInt(s.trim());
            medicineList.add(medicineMapper.findByMedicineID(id_int));
        }
        if(medicineList.isEmpty()){
            throw new NotFindException("未找到");
        }
        return medicineList;
    }
}
